package org.example;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Map;

/**
 * 配置加载类
 * 用于从YAML文件中加载应用程序配置
 */
public class ConfigLoader {
    private static final Map<String, Object> config;

    static {
        config = loadConfig();
    }

    /**
     * 加载配置文件
     *
     * @return 配置映射
     */
    private static Map<String, Object> loadConfig() {
        Yaml yaml = new Yaml();
        try (InputStream input = ConfigLoader.class.getClassLoader().getResourceAsStream("application.yml")) {
            if (input == null) {
                throw new RuntimeException("无法找到配置文件 application.yml");
            }
            return yaml.load(input);
        } catch (Exception e) {
            throw new RuntimeException("加载配置文件时出错: " + e.getMessage(), e);
        }
    }

    /**
     * 获取配置值
     *
     * @param key 配置键，支持点号分隔的嵌套键，如 "database.url"
     * @return 配置值
     */
    @SuppressWarnings("unchecked")
    public static String getProperty(String key) {
        String[] parts = key.split("\\.");
        Map<String, Object> current = config;

        for (int i = 0; i < parts.length - 1; i++) {
            Object next = current.get(parts[i]);
            if (!(next instanceof Map)) {
                return null;
            }
            current = (Map<String, Object>) next;
        }

        Object value = current.get(parts[parts.length - 1]);
        return value != null ? value.toString() : null;
    }

    /**
     * 获取配置值，如果不存在则返回默认值
     *
     * @param key          配置键
     * @param defaultValue 默认值
     * @return 配置值或默认值
     */
    public static String getProperty(String key, String defaultValue) {
        String value = getProperty(key);
        return value != null ? value : defaultValue;
    }
}
